import { readdirSync, statSync, writeFileSync } from "node:fs";
import path from "node:path";

/**
 * Recursively retrieves all file paths from the given directory.
 * @param dir - Directory to scan
 * @param baseDir - Base directory to preserve relative paths
 * @returns Array of file paths relative to the base directory
 */
function getAllFiles(dir: string, baseDir: string = dir): string[] {
  const entries = readdirSync(dir);
  const files: string[] = [];

  for (const entry of entries) {
    const fullPath = path.join(dir, entry);
    const stat = statSync(fullPath);

    if (stat.isDirectory()) {
      files.push(...getAllFiles(fullPath, baseDir));
    } else {
      files.push(path.relative(baseDir, fullPath));
    }
  }

  return files;
}

// Define the source directory
const distDir = path.join(__dirname, "../ui/dist");

// Get all files in the directory
const allFiles = getAllFiles(distDir);

// Generate import statements
const importStatements = allFiles.map((filePath) => {
  const importPath = `../ui/dist/${filePath.replace(/\\/g, "/")}`; // Normalize Windows backslashes to POSIX-style
  return `import "${importPath}" with {type: "file"}`;
});

// Define the output file path
const outputFilePath = path.join(__dirname, "autoimports.ts");

// Write the generated imports to the file
writeFileSync(outputFilePath, importStatements.join("\n"), "utf-8");
console.log(`Import statements written to ${outputFilePath}`);
